import * as types from "./action-types"
import axios from "../../../utils/axios"
import jwt_decode from 'jwt-decode'
import * as auth from "../../../utils/auth"

export const login = (user, token) => ({ type: types.LOGIN, user, token })
export const logout = () => ({ type: types.LOGOUT })

export const loginAsyn = (username, pwd) => {
    return (dispatch) => {
        const data = new FormData();
        data.append("openId", username);
        data.append("nickname", pwd);
        axios.post("/user/testLogin", data).then(res => {
            console.log(res);
            const decoded = jwt_decode(res.data)
            const obj = { id: decoded.id, nickname: decoded.nickname, avartar: decoded.avatar, expTime: decoded.exp }
            console.log(obj);
            auth.setAuth(obj, res.data)
            dispatch(login(obj, res.data))
        }).catch(error => {
            console.log(error);
        })
    }
}

export const logoutAsyn = () => {
    return (dispatch) => {
        auth.removeAuth()
        console.log("clear all auth");
        dispatch(logout())
    }
}